/**
 * 作者:hanbo
 * 日期:2018/12/2814:11
 * 描述:
 */
var useExtend;
require(["dojo/on", "dojo/dom", "myModule/Draw", "myModule/ExtendQuery", "dojo/domReady!"], function (on, dom, Draw, ExtendQuery) {
    //画线查询
    var btn_line = dom.byId("drawLine");
    on(btn_line, "click", function () {
        new Draw().drawPolyline(view, function (line) {
            new ExtendQuery(view).queryExtend(homeLayer, line);
        });
    });
    //画面查询
    var btn_area = dom.byId("drawArea");
    on(btn_area, "click", function () {
        new Draw().drawPolygon(view, function (polygon) {
            new ExtendQuery(view).queryExtend(homeLayer, polygon);
        });
    });
    var btn_query = dom.byId("conditionalQuery");
    on(btn_query, "click", function () {
        $("#dialog").dialog('open');
    });
    var btn_statics = dom.byId("statics");
    on(btn_statics, "click", function () {
        $("#dialog_statics").dialog('open');
    });

    var btn_drawExtent = dom.byId("drawExtent");
    on(btn_drawExtent, "click", function () {
        new Draw().drawPolygon(view, function (polygon) {
            useExtend = polygon;
            $('#costEstimate').removeClass('a_disable');
        });
    });

    var btn_extent_cost = dom.byId("costEstimate");
    on(btn_extent_cost, "click", function () {
        $("#dialog_extend").dialog('open');
    });
    var pointBuffer = dom.byId("pointBuffer");
    on(pointBuffer, "click", function () {
        var distance = $('#distance').numberspinner('getValue');
        var draw = new Draw();
        draw.drawPoint(view, function (point) {
            var buffer = draw.createBuffer(view, point, distance);
            new ExtendQuery(view).queryExtendFeature(homeLayer, buffer);
        });
    });
    var lineBuffer = dom.byId("lineBuffer");
    on(lineBuffer, "click", function () {
        var distance = $('#distance').numberspinner('getValue');
        var draw = new Draw();
        draw.drawPolyline(view, function (polyline) {
            var buffer = draw.createBuffer(view, polyline, distance);
            new ExtendQuery(view).queryExtendFeature(homeLayer, buffer);
        });
    });
    var areaBuffer = dom.byId("areaBuffer");
    on(areaBuffer, "click", function () {
        var distance = $('#distance').numberspinner('getValue');
        var draw = new Draw();
        draw.drawPolygon(view, function (polygon) {
            var buffer = draw.createBuffer(view, polygon, distance);
            new ExtendQuery(view).queryExtendFeature(homeLayer, buffer);
        });
    });

    var btn_import = dom.byId("import");
    on(btn_import, "click", function () {
        $("#dialog_choose").dialog('open');
    });

    require(["myModule/Edit"], function (Edit) {
        var edit = new Edit(view, homeLayer);

        $("#editBtn").click(function () {
            var state = $('#editBtn i');
            if (state.hasClass('checked')) {
                state.removeClass('checked');
                edit.stopEdit();
            } else {
                state.addClass('checked');
                edit.eidtAttributes();
            }
        });
    });
});

/**
 * 提交条件查询
 */
function submitForm() {
    $("#dialog").dialog('close');
    var sql = "";
    var belong = $("#dialog_belong").combo('getText');
    if (belong !== "") {
        sql = sql + "AND QSDWMC = '" + belong + "' "
    }
    var type = $("#dialog_type").combo('getText');
    if (type !== "") {
        sql = sql + "AND DLMC = '" + type + "' "
    }
    var people = $("#dialog_people").textbox('getText');
    if (people !== "") {
        sql = sql + "AND PEOPLE = '" + people + "' "
    }
    var dln = $("#dialog_dln").textbox('getText');
    if (dln !== "") {
        sql = sql + "AND DLBM = '" + dln + "' "
    }
    var tbn = $("#dialog_tbn").textbox('getText');
    if (tbn !== "") {
        sql = sql + "AND TBBH = '" + tbn + "' "
    }
    sql = sql.replace("AND", " AND");
    require(["myModule/ExtendQuery", "dojo/domReady!"], function (ExtendQuery) {
        new ExtendQuery(view).querySQL(homeLayer, sql);
    })
}

/**
 * 统计事件
 */
function subStatics() {
    $("#dialog_statics").dialog('close');
    // var type = $("#statics_type").radiobutton("options").checked;//所属村组统计
    var type = $(":radio[name='statics_type']:checked").val();
    type = Number(type);
    var title="";
    switch (type){
        case 0:
            title = "所属村组";
            break;
        case 1:
            title = "占地类型统计";
            break;
        case 2:
            title = $("#statics_base_s").combobox("getText");
            type=0;
            break;
        case 3:
            title = $("#statics_problem_s").combobox("getText");
            type=0;
            break;
        default:break;
    }
    require(["myModule/ExtendQuery", "dojo/domReady!"], function (ExtendQuery) {
        new ExtendQuery(view).statics(homeLayer, type,title);
    })

}

/**
 * 计算费用
 */
function calcuteCost() {
    $("#dialog_extend").dialog('close');
    var type = $("#cost_type").radiobutton("options").checked;
    var per_cost = $("#cost_per").textbox('getText');
    require(["myModule/ExtendQuery", "dojo/domReady!"], function (ExtendQuery) {
        var query = new ExtendQuery(view);
        if (type) {
            query.queryExtendArea(homeLayer, useExtend, per_cost)
        } else {
            query.staticsArea_people(homeLayer, useExtend, per_cost)
        }
    });

}

function commitFile() {
    $("#dialog_choose").dialog('close');
    var json = $("#jsonResult").textbox("getText");
    require(["esri/tasks/support/FeatureSet", "esri/Graphic"], function (FeatureSet, Graphic) {
        var sets = FeatureSet.fromJSON(JSON.parse(json));
        var graphics = [];
        var polylineSymbol = {
            type: "simple-line",  // autocasts as SimpleLineSymbol()
            color: [226, 119, 40],
            width: 4
        };
        for (var i = 0; i < sets.features.length; i++) {

            graphics.push(new Graphic({
                geometry: sets.features[i].geometry,
                symbol: polylineSymbol,
                attributes: sets.features[i].attributes
            }))
        }
        view.graphics.addMany(graphics);
    });
}

function readJson() {
    var selectedFile = document.getElementById("chooseFile").files[0];

    var reader = new FileReader();//这里是核心！！！读取操作就是由它完成的。
    reader.readAsText(selectedFile);//读取文件的内容

    reader.onload = function () {
        var json = this.result;
        $("#jsonResult").textbox("setText", json);
    };
}

function applyDraw() {
    closeApply();
    require(["myModule/Draw"], function (Draw) {
        var draw = new Draw();
        draw.drawPolygon(view, function (polygon) {
            openApply();
            $('#apply_area').numberbox('setValue', Math.abs(draw.getArea(polygon)));
        });
    });
}

function closeApply() {
    view.graphics.removeAll();
    $("#dialog_apply").dialog('close');
}

function openApply() {
    $("#dialog_apply").dialog('open');
}

function exportData() {
    require(["myModule/Draw", "myModule/ExtendQuery"], function (Draw, ExtendQuery) {
        new Draw().drawPolygon(view, function (polygon) {
            new ExtendQuery(view).queryExport(homeLayer, polygon);
        });
    });
}

/**
 * 发证
 */
function makeCertificate() {
    require(["myModule/Draw", "myModule/ExtendQuery"], function (Draw, ExtendQuery) {
        new Draw().drawPoint(view, function (polygon) {
            new ExtendQuery(view).queryPrint(homeLayer, polygon);
        });
    });
}

function approval() {
    $("#approvalWindow").panel('open');
    $('#approvalTable').datagrid({
        fitColumns: true,
        singleSelect: true,
        idField: "FID",
        columns: [[
            {field: 'FID', title: '编号', width: 100, align: 'center'},
            {field: 'PEOPLE', title: '使用人姓名', width: 100, align: 'center'},
            {field: 'AREA', title: '面积', width: 100, align: 'center'},
            {field: 'QSDWMC', title: '所属村组', width: 100, align: 'center'},
            {field: 'DLMC', title: '占地类型', width: 100, align: 'center'},
            {
                field: 'position', title: '位置', align: 'center', width: $(this).width() * 0.1,
                formatter: function (value, row) {
                    var str = '<a href="#"  onclick="zoomTo(' + row.x + ',' + row.y + ')" class="easyui-linkbutton" >查看位置</a>';
                    return str;
                }
            },
            {
                field: 'operate', title: '操作', align: 'center', width: $(this).width() * 0.1,
                formatter: function (value, row) {
                    var str = '<a href="#" class="easyui-linkbutton" onclick="deleteRow(' + row.FID + ')" >通过</a>  <a href="#" onclick="deleteRow(' + row.FID + ')" class="easyui-linkbutton" >不通过</a>';
                    return str;
                }
            }

        ]]
    });

    $.ajax({
        url: "data/approval.json", dataType: "json", success: function (e) {
            var data = [];
            for (var i = 0; i < e.features.length; i++) {
                data.push(e.features[i].attributes);
            }
            $('#approvalTable').datagrid('loadData', data);
        }
    });

}

function zoomTo(x, y) {
    require(["esri/geometry/Point", "esri/Viewpoint"], function (Point, Viewpoint) {
        var point = new Point({
            hasZ: false,
            hasM: false,
            x: x,
            y: y,
            spatialReference: {
                wkid: 3857
            }
        });
        var viewPoint = new Viewpoint({
            targetGeometry: point,
            scale: 500
        });
        view.goTo(viewPoint).then(function () {
            var screenPoint = view.toScreen(point);
            view.hitTest(screenPoint).then(function (response) {
                var results = response.results;
                if (results.length > 0 && results[0].graphic && results[0].graphic.layer === homeLayer) {
                    view.popup.open({
                        features: [results[0].graphic]
                    })
                }
            });
        });
    });

}

function deleteRow(fid) {
    var index = $('#approvalTable').datagrid("getRowIndex", fid);
    $('#approvalTable').datagrid("deleteRow", index);
}

function changePeople() {
    require(["myModule/Draw", "myModule/ExtendQuery"], function (Draw, ExtendQuery) {
        new Draw().drawPoint(view, function (polygon) {
            new ExtendQuery(view).queryChange(homeLayer, polygon);
        });
    });
}

function submitChange() {
    $("#changeWindow").panel('close');
    $.messager.alert('提示', '上传成功');
}

/**
 * 展示人员管理页面
 */
function showUserManager() {
    var box = $("<div id='userManager'><iframe src='innerPages/userCenter.html' style='height: 100%;width: 100%'></iframe></div>");
    $("body").append(box);
    $('#userManager').window({
        width: 700,
        height: 300,
        title: '用户管理',
        resizable: true,
        modal: true,
        onClose: function () {
            $('#userManager').window("destroy")
        }
    });
}

function showPrivilegeManager() {
    var box = $("<div id='userManager'><iframe src='innerPages/privilegeManagement.html' style='height: 100%;width: 100%'></iframe></div>");
    $("body").append(box);
    $('#userManager').window({
        width: 700,
        height: 300,
        title: '权限管理',
        resizable: true,
        modal: true,
        onClose: function () {
            $('#userManager').window("destroy")
        }
    });
}

function showObligee(number) {
    var html="";
    var title="";
    switch (number){
        case 0:
            html="obligee.html";
            title="权利人管理";
            break;
        case 1:
            html="homestead.html";
            title="宗地管理";
            break;
        case 2:
            html="house.html";
            title="房屋管理";
            break;
        case 3:
            html="marker.html";
            title="界址点管理";
            break;
        case 4:
            html="line.html";
            title="界址线管理";
            break;
        default:break;
    }


    var box = $("<div id='userManager'><iframe src='innerPages/"+html+"' style='height: 100%;width: 100%'></iframe></div>");
    $("body").append(box);
    $('#userManager').window({
        width: 900,
        height: 300,
        title: title,
        resizable: true,
        modal: true,
        onClose: function () {
            $('#userManager').window("destroy")
        }
    });
}

/**
 * 新宅选址
 */
function siteSelection() {
    require(["esri/tasks/Geoprocessor"], function (Geoprocessor) {
        //地理处理服务的地址，为GPServr地址+模型名称
        var gpUrl =
            "http://localhost:6080/arcgis/rest/services/inter2/GPServer/inter2";
        var gp = new Geoprocessor(gpUrl);
        gp.outSpatialReference = { // 输出坐标系
            wkid: 4326
        };

        view.graphics.removeAll();

        var params = {};
        showLoading();
        //同步异步和服务器的设置有关
        // 进行异步查询，使用gp.excute为同步查询
        gp.submitJob(params).then(drawResultData, outError);
        //进行同步查询
        // gp.execute(params).then(drawResult,outError);

        //接收异步结果，进行绘制
        function drawResultData(result) {
            console.log("分析完成");
            console.log(result);
            var jobId = result.jobId;
            //可视域填充样式
            var fillSymbol = {
                type: "simple-fill", // autocasts as new SimpleFillSymbol()
                color: [226, 119, 40, 0.75],
                outline: { // autocasts as new SimpleLineSymbol()
                    color: [255, 255, 255],
                    width: 1
                }
            };
            //根据jobID获取分析结果
            //下面的第二个参数为，发布服务时，看到的结果参数的名称
            gp.getResultData(jobId, "result").then(function (value) {
                console.log("查询完成");
                hideLoading();
                var resultFeatures = value.value.features;
                // 给每一个结果添加样式
                var viewshedGraphics = resultFeatures.map(function (feature) {
                    feature.symbol = fillSymbol;
                    return feature;
                });

                // 从俯视状态看结果
                view.graphics.addMany(viewshedGraphics);
                view.goTo({
                    target: viewshedGraphics,
                    tilt: 0
                });
                homeLayer.visible = false;
            }, outError)
        }

        function outError(e) {
            console.error(e)
            hideLoading();
        }
    });
}

$(function () {
    $("#statics_base").radiobutton({
        onChange: function (state) {
            if (state) {
                $("#statics_base_s").combobox("enable");
            } else {
                $("#statics_base_s").combobox("disable")
            }
        }
    });
    $("#statics_problem").radiobutton({
        onChange: function (state) {
            if (state) {
                $("#statics_problem_s").combobox("enable")
            } else {
                $("#statics_problem_s").combobox("disable")
            }
        }
    });
});


